import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/homeView/HomeView.vue'
import { checkTokenAndFetchUserInfo } from '@/utils/auth';



const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/login',
      name: 'login',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/loginView/LoginView.vue')
    },
    {
      path: '/form',
      name: 'form',
      component: () => import('../views/formView/formView.vue')
    },
    {
      path: '/userinfo',
      name: 'userinfo',
      component: () => import('../views/userInfoView/userInfoView.vue')
    },
    {
      path: '/demandinfo',
      name: 'demandinfo',
      component: () => import('../views/demandInfoView/demandInfoView.vue')
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return { left: 0, top: savedPosition.top };
    } else if (to.hash) {
      return {
        el: to.hash,
        behavior: 'smooth'
      };
    } else {
      return { left: 0, top: 0 };
    }
  }
})


router.beforeEach(async (to, from, next) => {
  await checkTokenAndFetchUserInfo();
  next();
});

export default router
